/*
 * Copyright (c) 2010, Petr Panteleyev <petr@panteleyev.org>
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *    1. Redistributions of source code must retain the above copyright notice, 
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice, 
 *       this list of conditions and the following disclaimer in the documentation 
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products 
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN 
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.flickr;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import org.panteleyev.blogclient.BloggerEditorFrame;
import org.panteleyev.blogclient.IPicturePublishDialog;
import org.panteleyev.blogclient.PublishTargetPanel;
import org.panteleyev.blogclient.UserProfileManager;
import org.panteleyev.blogclient.photo.ThumbnailsPublishPanel;
import org.panteleyev.flickrapi.FlickrPhoto;
import org.panteleyev.flickrapi.PhotoSize;
import org.panteleyev.flickrapi.PhotoSizeType;
import org.panteleyev.flickrapi.SizeTable;
import org.panteleyev.photo.Thumbnail;
import org.panteleyev.swing.BasicDialog;
import org.panteleyev.swing.OkCancelButtonPanel;
import org.panteleyev.swing.SwingFactory;
import org.panteleyev.swing.SwingWorkerEx;

import com.google.common.collect.ImmutableList;

/**
 * @author peterp
 *
 */
final class PublishPicturesDialog extends BasicDialog<JFrame> implements IPicturePublishDialog {    
    private FLUserProfile   profile;
    
    // UI
    private JCheckBox               useTableCheckBox;
    private JComboBox               columnsComboBox;
    private JCheckBox               tableBorderCheckBox;
    private JCheckBox               titleCheckBox;
    private JComboBox               thumbSizeList;
    private JCheckBox               imageBorderCheckBox;
    private PublishTargetPanel      targetPanel;
    private ThumbnailsPublishPanel<FlickrPhoto>  thumbnailsPanel;

    public PublishPicturesDialog(JFrame parent, FLUserProfile profile, final ImmutableList<FlickrPhoto> pictures) {
        super(parent);
        this.profile = profile;
        
        initComponents();
        setResizable(true);
        
        new SwingWorkerEx<Object,Object>(this) {
            private ArrayList<Thumbnail<FlickrPhoto>> thumbnails = new ArrayList<Thumbnail<FlickrPhoto>>();

            @Override
            protected Object doInBackground() throws Exception {
                for (final FlickrPhoto pict : pictures) {
                    SizeTable sizes = getProfile().getPhotoSizes(pict);
                    if (sizes == null || sizes.get(PhotoSizeType.MEDIUM640.value()) == null) {  
                        // make sure cached photo has updated size table -^
                        sizes = getProfile().getAccount().getSizes(pict);
                        getProfile().addPhotoSize(pict, sizes);
                    }
                    
                    PhotoSize size = sizes.get(PhotoSizeType.THUMBMNAIL.value());
                    ImageIcon image = UserProfileManager.loadThumbnailFromNetwork(getProfile(), size.getSource());
                    thumbnails.add(new Thumbnail<FlickrPhoto>(image, pict.getTitle(), pict));
                }
                return null;
            }
            @Override
            protected void done() {
                thumbnailsPanel.setContent(thumbnails);
                super.done();
            }
        }.execute();        
    }
    
    private FLUserProfile getProfile() {
        return profile;
    }

    private void initComponents() {
        setTitle(TITLE);
        getContentPane().setLayout(new BorderLayout());
        JPanel tablePanel;
        
        final AbstractAction useTableAction = new AbstractAction(USE_TABLE) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                final boolean b = useTableCheckBox.isSelected();
                columnsComboBox.setEnabled(b);
                tableBorderCheckBox.setEnabled(b);
                titleCheckBox.setEnabled(b);
            }            
        };
        
        JPanel mainPanel = SwingFactory.createPanel(null, SwingFactory.LAYOUT.BOX_Y,
            tablePanel = SwingFactory.createPanel(
                BorderFactory.createTitledBorder(TABLE), SwingFactory.LAYOUT.BOX_Y,
                useTableCheckBox = new JCheckBox(useTableAction),
                SwingFactory.createPanel(null, SwingFactory.LAYOUT.BOX_X,
                    new JLabel(COLUMNS),
                    Box.createHorizontalStrut(3),
                    columnsComboBox = new JComboBox(new String[] { "1", "2", "3", "4" }),
                    Box.createHorizontalStrut(5),
                    tableBorderCheckBox = new JCheckBox(BORDER),
                    Box.createHorizontalStrut(5),
                    titleCheckBox = new JCheckBox(ITEM_TITLE),
                    Box.createHorizontalGlue()
                )
            ),
            SwingFactory.createPanel(
                BorderFactory.createTitledBorder(LINK), SwingFactory.LAYOUT.BOX_X,
                new JLabel(THUMBNAIL),
                Box.createHorizontalStrut(3),
                thumbSizeList = new JComboBox(PhotoSizeType.values()),
                Box.createHorizontalStrut(5),
                imageBorderCheckBox = new JCheckBox(BORDER),
                Box.createHorizontalGlue()
            ),
            targetPanel = new PublishTargetPanel()
        );
        SwingFactory.setAlignmentX(tablePanel, LEFT_ALIGNMENT);
        SwingFactory.setAlignmentX(mainPanel, LEFT_ALIGNMENT);
        thumbSizeList.setSelectedIndex(1);
        useTableCheckBox.setSelected(true);
        
        JTabbedPane pane = new JTabbedPane();
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(mainPanel, BorderLayout.NORTH);
        pane.add(SETTINGS, panel);
        pane.add(PHOTOS, thumbnailsPanel = new ThumbnailsPublishPanel<FlickrPhoto>());

        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(new OkCancelButtonPanel(this), BorderLayout.SOUTH);        
    }
    
    public Thumbnail<FlickrPhoto> getThumbnail(int index) {
        return thumbnailsPanel.getThumbnail(index);        
    }
    
    public PhotoSizeType getThumbnailSize() {
        return (PhotoSizeType)thumbSizeList.getSelectedItem();
    }

    public boolean getTableBorder() {
        return tableBorderCheckBox.isSelected();
    }

    public boolean getImageBorder() {
        return imageBorderCheckBox.isSelected();
    }

    public int getColumnCount() {
        return columnsComboBox.getSelectedIndex() + 1;
    }    
    
    BloggerEditorFrame<?> getDestinationWindow() {
        return targetPanel.getDestinationWindow();
    }
    
    public boolean isAddTitle() {
        return titleCheckBox.isSelected();
    }
    
    public boolean isUseTable() {
        return useTableCheckBox.isSelected();
    }    
}
